package sel.me.popular.library.learning.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import sel.me.popular.library.learning.disruptor.event.LongEvent;

import java.nio.ByteBuffer;

/**
 * Disruptor API的设计影响之一是Java 8将依赖功能接口的概念作为Java Lambdas的类型声明
 * 。Disruptor API中的大多数接口定义符合功能接口的要求，因此可以使用Lambda而不是自定义类
 * ，这可以减少所需的boiler place
 *
 * @author shenenlu 2021年05月14日 上午10:41:14
 */
public class LongEventMain {

    public static void main(String[] args) throws Exception{
        // Specify the size of the ring buffer, must be power of 2.
        int bufferSize = 1024;

        // Construct the Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, bufferSize
                , DaemonThreadFactory.INSTANCE);

        // Connect the handler
        disruptor.handleEventsWith((event, sequence, endOfBatch) -> System.out.println("Event: " + event));

        // Start the Disruptor, starts all threads running
        disruptor.start();

        // Get the ring buffer from the Disruptor to be used for publishing.
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; true; l++){
            bb.putLong(0, l);
            ringBuffer.publishEvent((event, sequence, buffer) -> event.set(buffer.getLong(0)), bb);
            Thread.sleep(1000);
        }
    }

}
